package com.mobialia.wikiplaces;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WikiplacesAdapter extends BaseAdapter {

	private Context mContext;
	WikiplacesData wikiplacesData;
	SharedPreferences sharedPreferences;

	public WikiplacesAdapter(Context c) {
		mContext = c;
		wikiplacesData = WikiplacesData.getInstance(c);
		sharedPreferences = PreferenceManager.getDefaultSharedPreferences(c);
	}

	public int getCount() {
		return wikiplacesData.getSize();
	}

	public Wikiplace getObject(int position) throws JSONException {
		return (Wikiplace) wikiplacesData.getWikiplace(position);
	}
	
	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		LinearLayout ll;
		
		if (convertView != null) {
			ll = (LinearLayout) convertView;
		} else {
			ll = (LinearLayout) LayoutInflater.from(mContext).inflate(
				R.layout.wikiplaces_adapter, parent, false);
		}
		
		Wikiplace wikiplace = wikiplacesData.getWikiplace(position);

		TextView title = (TextView) ll.findViewById(R.id.Title);
		title.setText(wikiplace.getTitle());
		
		TextView distance = (TextView) ll.findViewById(R.id.Distance);
		NumberFormat formatter = new DecimalFormat("0.00");
		if ("km".equals(sharedPreferences.getString("units", "km"))) {
			distance.setText(formatter.format(wikiplace.getDistance()) + " Km");			
		} else {
			distance.setText(formatter.format(wikiplace.getDistance() * 0.621371192) + " Mi");
		}
		
		return ll;
	}
}
